"ui";

const LEFT = 1, RIGHT = 2;
const UI_CHAT = 1,UI_RECALLING = 2,UI_OTHER = 3;
const TEXT_TYPE = 1, EMOJI_TYPE = 2, OTHER_TYPE = 3;
var 聊天信息, 输入框;
const MSG_MAX_SIZE = 50,CONTENT_SIZE = 8,HISTORY_CONTENT_SIZE = 5;
var MsgListPositions = new Array(MSG_MAX_SIZE);
var msgPosList_temp = new Array(MSG_MAX_SIZE);//left,right,top,bottom,类型,值,(左or右),发送人名字
var RecallListPositions = new Array(MSG_MAX_SIZE);//维护撤回标志
var recallList_temp = new Array(MSG_MAX_SIZE);
var vis_head =  new Array(MSG_MAX_SIZE);
var remove_used_position = new Array(MSG_MAX_SIZE);
var msg_box = [];//消息盒子
const EPS = 5;//误差
const PACKAGE_WECHAT = "com.tencent.mm";

var msg_recall_box = [];
var is_multi_chat_reply = true,is_at_reply=true,is_screenshot_recall = true,close_auto_reply = false;//群聊自动回复,艾特才回复,截屏保存撤回内容
var file_id = 1;
const FILE_PATH = files.getSdcardPath() + "/微信消息截图/";//消息的截图的保存目录
const SCREENSHOT_PATH = files.getSdcardPath() +"/SCREEN_SHOT.png";//默认截图路径
const DEFAULT_FILE_NAME = "ERR";
const IMAGE_FILE_PATH = files.getSdcardPath() +"/NEWEST_IMAGE.png";//生成最新的图片

var robot_is_running = false,is_auto_clear = true;

const SINGLE_CHAT_MODE = 1,MULTI_CHAT_MODE = 2,OTHER_CHAT_MODE = 3,MULTICHAT_REG = /.+\([1-9][0-9]*\)/;
var default_nickname = "我的默认群昵称",my_nickname = default_nickname,chatObject_name="UnKnow";//当前的聊天对象名字
var curr_chat_mode = OTHER_CHAT_MODE;

var window,window_,ad,ad_,F,F_;

var storage = storages.create("keylist_wechat_biggestfan");
//从storage获取keyReplyList,//name,keyword,reply,enable,reg_enable
var keyReplyList = storage.get("key_items", [
    {
        name: "kiwi",
        keyword: "开黑",
        keyreply: "好的,马上到。",
        enable: true,
        reg_enable:false,
    },
    {
        name: "*",
        keyword: "开黑",
        keyreply: "滚滚滚,我只和kiwi开黑。",
        enable: true,
        reg_enable:false,
    },
    {
        name: ".+",
        keyword: "(?:q|Q){2}\\s?[1-9][0-9]{4,}",
        keyreply: "这是一个qq号码(qq匹配示例)。",
        enable: true,
        reg_enable:true,
    },
]);
ui.layout(
    <drawer id="drawer" >
        <vertical>
            <appbar>
                <toolbar id="toolbar" title="微信聊天机器人" bg =  "#E9967A"/>
                <tabs id="tabs" bg =  "#E9967A"/>
            </appbar>
            <viewpager id="viewpager" >
                <frame >
                    <vertical>
                        <img scaleType="fitStart" w="*" h="auto" src="https://img.ivsky.com/img/bizhi/pre/201801/21/darling_in_the_franxx-008.jpg"/>
                        <button id = "script_start" textSize="16sp" layout_gravity="center" textColor="#E9967A" text="开始运行" style="Widget.AppCompat.Button.Borderless.Colored" w="auto"/>
                    </vertical>
                </frame>
                <frame>
                    <vertical>
                        <list id="keywordlist">
                                <horizontal gravity="center_vertical">
                                    <vertical>
                                        <checkbox text = "启用" id="enable__" marginLeft="4" marginRight="6" checked="{{this.enable}}" />
                                        <checkbox text = "正则" id="regenable__" marginLeft="4" marginRight="6" checked= "{{this.reg_enable}}" />
                                    </vertical>
                                    <vertical padding="10 8" h="auto" w="auto" >
                                        <horizontal>
                                            <text text="好友备注: " textColor="#999999" textSize="16sp" maxLines="1"/>
                                            <text text="{{this.name}}" textColor="#222222" textSize="16sp" maxLines="1" />
                                        </horizontal>
                                        <horizontal>
                                            <text text="关键字: " textColor="#999999" textSize="16sp" maxLines="1"/>
                                            <text text="{{this.keyword}}" textColor="#222222" textSize="16sp" maxLines="1" />
                                        </horizontal>
                                        <horizontal>
                                            <text text="回复: " textColor="#999999" textSize="16sp" maxLines="1"/>
                                            <text text="{{this.keyreply}}" textColor="#222222" textSize="16sp" maxLines="1" />
                                        </horizontal>
                                    </vertical>
                                </horizontal>
                        </list>
                    </vertical>
                    <fab id="add" w="auto" h="auto" src="@drawable/ic_add_black_48dp"
                        margin="16" layout_gravity="bottom|right" tint="#ffffff" />
                </frame>
                <frame>
                    <vertical padding="16">
                        <img scaleType="fitStart" w="*" h="auto" src="https://img.ivsky.com/img/bizhi/pre/201801/21/darling_in_the_franxx-004.jpg"/>
                        {/* <text margin="8" textSize="16sp" textColor="#E9967A" 
                            text= '说明:自定义回复在私聊或群聊都适用;只有启用的自定义回复才会激活;自定义回复使用的是好友备注,而不是好友昵称,好友群昵称或者其它;当好友备注设置为*时,表示匹配任意好友;长按列表可以删除自定义回复;'/> */}
                        <text margin="8" textSize="16sp" textColor="#E9967A" text= '说明:'/>
                        <text margin="8" textSize="16sp" textColor="#E9967A" text= '自定义回复在私聊或群聊都适用，只有启用的自定义回复才会激活。'/>
                        <text margin="8" textSize="16sp" textColor="#E9967A" text= '自定义回复使用的是好友备注,而不是好友昵称,好友群昵称或者其它。'/>
                        <text margin="8" textSize="16sp" textColor="#E9967A" text= '未开启正则时,当好友备注设置为*时,表示匹配任意好友。'/>
                        <text margin="8" textSize="16sp" textColor="#E9967A" text= '开启正则时,好友备注和关键字都会使用正则匹配。'/>
                        <text margin="8" textSize="16sp" textColor="#E9967A" text= '正则表达式由字符串构造,请不要写成字面量/reg/的形式,也不要添加起始符^和结束符$,同时需要注意表达式的反斜杠。'/>
                        <text margin="8" textSize="16sp" textColor="#E9967A" text= '长按列表可以删除自定义回复。'/>
                        <text margin="8" textSize="16sp" textColor="#E9967A" text= '一条消息匹配多个自定义回复时，优先选择上面的自定义回复。'/>
                    </vertical>
                    
                </frame>
            </viewpager>
        </vertical>
    </drawer>
);

//定义一个悬浮窗控制组件(window:悬浮窗，windowid:用来控制悬浮窗移动的控件)
var 悬浮控制 = function(window, windowid, ar) {
    this.Orientation = context.resources.configuration.orientation;
    this.Width = this.Orientation == 1 ? device.width : device.height;
    this.Height = this.Orientation == 2 ? device.width : device.height;
    this.isAutoIntScreen = true;
    this.Click = function() {};
    this.Move = function() {};
    this.LongClick = function() {};
    this.setClick = (fun) => {
        fun = fun || function() {};
        this.Click = fun;
    };
    this.setMove = (fun) => {
        fun = fun || function() {};
        this.Move = fun;
    };
    this.setLongClick = (fun, ji) => {
        fun = fun || function() {};
        this.LongClick = fun;
        if (parseInt(ji)) {
            this.Tjitime = parseInt(ji) / 50;
        };
    };
    setInterval(() => {
        if (context.resources.configuration.orientation != this.Orientation) {
            this.Orientation = context.resources.configuration.orientation;
            this.Width = this.Orientation == 1 ? device.width : device.height;
            this.Height = this.Orientation == 2 ? device.width : device.height;
            var xy = this.windowGXY(window.getX(), window.getY(), this.G(window));
            this.windowyidong([
                [window.getX(), window.getY()],
                [xy.x, xy.y]
            ]);
        };
    }, 100);
    this.TX = 0;
    this.TY = 0;
    this.Tx = 0;
    this.Ty = 0;
    this.Tyidong = false;
    this.Tkeep = false;
    this.Tjitime = 12;
    this.Ttime = 0;
    setInterval(() => {
        if (this.Tkeep) {
            this.Ttime++;
            if (!this.Tyidong && this.Ttime > this.Tjitime) {
                //非移动且按下时长超过1秒判断为长按
                this.Tkeep = false;
                this.Ttime = 0;
                this.LongClick();
            };
        };
    }, 50);
    if (windowid) {
        windowid.setOnTouchListener(new android.view.View.OnTouchListener((view, event) => {
            this.Move(view, event);
            switch (event.getAction()) {
                case event.ACTION_DOWN:
                    this.Tx = event.getRawX();
                    this.Ty = event.getRawY();
                    this.TX = window.getX();
                    this.TY = window.getY();
                    this.Tkeep = true; //按下,开启计时
                    break;
                case event.ACTION_MOVE:
                    var sx = event.getRawX() - this.Tx;
                    var sy = event.getRawY() - this.Ty;
                    if (!this.Tyidong && this.Tkeep && this.weiyi(sx, sy) >= 10) {
                        this.Tyidong = true;
                    };
                    if (this.Tyidong && this.Tkeep) {
                        window.setPosition(this.TX + sx, this.TY + sy);
                    };
                    break;
                case event.ACTION_UP:
                    if (!this.Tyidong && this.Tkeep && this.Ttime < 7) {
                        this.Click();
                    };
                    this.Tkeep = false;
                    this.Ttime = 0;
                    if (this.Tyidong) {
                        if (this.isAutoIntScreen) {
                            threads.start(new java.lang.Runnable(() => {
                                this.windowyidong(this.IntScreen());
                            }));
                        } else {
                            threads.start(new java.lang.Runnable(() => {
                                this.windowyidong(this.ViewIntScreen());
                            }));
    
                        };
                        this.Tyidong = false;
                    };
                    break;
            };
            return true;
        }));
    };
    this.G = (win, view) => {
        //返回悬浮窗的坐标范围。
        var K = 36, //悬浮窗的隐形边矩
            H = 66; //手机通知栏的高度
        var ary;
        if (!ar) {
            if (view) {
                ary = [
                    [-view.getX(), -view.getY()],
                    [this.Width - (view.getX() + view.getWidth()), this.Height - (view.getY() + view.getHeight()) - H - K]
                ];
    
            } else {
                ary = [
                    [0, 0],
                    [this.Width - win.getWidth() + K * 2, this.Height - win.getHeight() - H + K * 2]
                ];
            }
        } else {
            if (view) {
                ary = [
                    [-view.getX(), H - view.getY()],
                    [this.Width - (view.getX() + view.getWidth()), this.Height - (view.getY() + view.getHeight())]
                ];
    
            } else {
                ary = [
                    [0, H],
                    [this.Width - win.getWidth(), this.Height - win.getHeight()]
                ];
            }
        };
        return ary;
    };
    this.weiyi = function() { //平方和开方
        var num = 0;
        for (var i = 0; i < arguments.length; i++) {
            num += arguments[i] * arguments[i];
        };
        return Math.round(Math.sqrt(num) * 1000) / 1000
    };
    this.windowGXY = function(x, y, k) {
        //修正坐标的所在范围。如果坐标超出了范围，则修正回来。
        x = (k[0][0] < x && x < k[1][0]) ? x : (k[0][0] < x ? k[1][0] : k[0][0]);
        y = (k[0][1] < y && y < k[1][1]) ? y : (k[0][1] < y ? k[1][1] : k[0][1]);
        return {
            x: x,
            y: y
        };
    };
    this.windowyidong = (A, s, w) => {
        //移动悬浮窗的动画效果。
        w = w || window;
        s = s || 10;
        var sx = A[1][0] - A[0][0],
            sy = A[1][1] - A[0][1];
        var sd = this.weiyi(sx, sy) / s;
        var X = sx / sd,
            Y = sy / sd;
        var x = 0,
            y = 0;
        for (var i = 0; i < sd; i++) {
            x += X;
            y += Y;
            sleep(1);
            w.setPosition(A[0][0] + x, A[0][1] + y);
        };
        w.setPosition(A[1][0], A[1][1]);
    };
    this.OutScreen = () => {
        //算出最短的距离到达屏幕之外。
        var F = this.G(window);
        var x = window.getX(),
            y = window.getY();
        var sx = window.getX() + window.getWidth() / 2,
            sy = window.getY() + window.getHeight() / 2 + 66;
        var cx = Math.abs(sx < (this.Width - sx) ? sx : (this.Width - sx)) < Math.abs(sy < (this.Height - sy) ? sy : (this.Height - sy)) ? (sx < this.Width / 2 ? (F[0][0] - window.getWidth()) : (F[1][0] + window.getWidth())) : x,
            cy = Math.abs(sx < (this.Width - sx) ? sx : (this.Width - sx)) < Math.abs(sy < (this.Height - sy) ? sy : (this.Height - sy)) ? y : (sy < this.Height / 2 ? (F[0][1] - window.getHeight()) : (F[1][1] + window.getHeight()));
        return [
            [x, y],
            [cx, cy]
        ];
    };
    this.toScreenEdge = (d) => {
        //返回到屏幕边缘的坐标。d为浮点数0.1~1之间。
        d = d || 0;
        var F = this.G(window);
        var x = window.getX(),
            y = window.getY();
        var sw = window.getWidth() * d;
        var sx = window.getX() + window.getWidth() / 2,
            sy = window.getY() + window.getHeight() / 2 + 66;
        var cx = sx < (this.Width - sx) ? -sw : (this.Width + sw - window.getWidth() + 72);
        return [
            [x, y],
            [cx, y]
        ];
    };
    this.centerXY = (F) => {
        //返回距离中心位置的一个方形两个坐标。
        var w = window.getWidth();
        var h = window.getHeight();
        return [
            [F[0] + w / 2, F[1] + h / 2],
            [F[0] - w / 2, F[1] - h / 2]
        ];
    };
    this.IntScreen = () => {
        //当悬浮超出屏幕之外之后进入的坐标。
        var A = this.windowGXY(window.getX(), window.getY(), this.G(window));
        return [
            [window.getX(), window.getY()],
            [A.x, A.y]
        ];
    };
    this.ViewIntScreen = () => {
        //当悬浮超出屏幕之外之后进入的坐标。
        var A = this.windowGXY(window.getX(), window.getY(), this.G(window, windowid));
        return [
            [window.getX(), window.getY()],
            [A.x, A.y]
        ];
    };
    threads.start(new java.lang.Runnable(() => {
        this.windowyidong(this.IntScreen());
    }));
 };

function create_floaty()
{
    //w:属性width的缩写形式。可以设置的值为*, auto和具体数值。其中*表示宽度尽量填满父布局，而auto表示宽度将根据View的内容自动调整(自适应宽度)
    //定义一个主悬浮窗
    window = floaty.window(
        <vertical bg="#ffeeeeee" padding="5" h="{{Math.floor(device.height*0.6)}}px" w="{{Math.floor(device.width*0.55)}}px">
            <list layout_weight="7" id="list" w="*" h="0dp" bg="#FFF0F5">
                <text w="*" h="50" text="{{txt}}" textSize="13sp" bg="#dddddd" margin="1" gravity="center"/>
            </list>
            <webview layout_weight="2" id="web" w = "*" h= "0dp" bg="#FFF0F5" />
            <horizontal layout_weight="1" w="*" h = "0dp"  >
                <checkbox id="close_re" text="关闭回复" checked="false" layout_weight="1"/>
                <checkbox id="multi_re" text="群聊回复" checked="true" layout_weight="1"/>
                <checkbox id="at_re" text="at回复" checked="true" layout_weight="1"/>
            </horizontal>
            <horizontal layout_weight="1" w="*" h = "0dp"  >
                <checkbox id="msg_screen" text="消息截屏" checked="true" layout_weight="1"/>
                <checkbox id="clear" text="自动清理" checked="true" layout_weight="1"/>
            </horizontal>
            <horizontal layout_weight="1" w="*" h = "0dp"  >
                <button id="robot_control"  text="开始运行" layout_weight="1" />
                <button id="robot_exit"  text="关闭脚本" layout_weight="1" />
            </horizontal>
            <horizontal layout_weight="1" w="*" h = "0dp"  >
                <button id="move"  text="移动及最小化" layout_weight="1" />
            </horizontal>
            
        </vertical>
    );

    //定义一个最小化的悬浮窗
    window_ = floaty.window(
        <button id="but_" w="150px" h="150px" text="▽" alpha="0.7"/>
     );
        
    /*
    两个悬浮窗之间的联动
    */
    ad = new 悬浮控制(window, window.move);
    ad.isAutoIntScreen = false;
    ad_ = new 悬浮控制(window_, window_.but_);
    ad.setLongClick(exit);
    ad_.setLongClick(exit);
    F = ad.OutScreen();
    F_ = ad_.OutScreen();
    
    threads.start(function() {
    sleep(100);
    F_ = ad_.OutScreen();
    ad_.windowyidong(F_);
    });
    
    ad.setClick(function() {
    window.disableFocus();
    threads.start(function() {
        F = ad.OutScreen();
        ad.windowyidong(F);
        ad_.windowyidong([F_[1], ad_.centerXY(ad.centerXY(F[0])[0])[1]]);
        ad_.windowyidong(ad_.IntScreen());
        ad_.windowyidong(ad_.toScreenEdge(0));
    });
    });
    
    ad_.setClick(function() {
    window.disableFocus();
    threads.start(function() {
        F_ = ad_.OutScreen();
        ad_.windowyidong(F_);
        ad.windowyidong([F[1], ad.centerXY(ad_.centerXY(F_[0])[0])[1]]);
        ad.windowyidong(ad.IntScreen());
    });
    });
}
// create_floaty();

function init_floaty()
{
    ui.run(() => {
        window.list.setVisibility(0);
        window.web.setVisibility(0);
        window.list.setDataSource(msg_recall_box);
    });
    
    window.list.on("item_click", function(item, i) {
        setClip(item.txt);
        ui.run(() => {
            if(files.exists(item.src))
            {
                window.web.loadUrl("file:"+item.src);
                threads.start(function(){
                    files.remove(IMAGE_FILE_PATH);
                    files.copy(item.src, IMAGE_FILE_PATH);
                    media.scanFile(IMAGE_FILE_PATH);
                });
            }
            else toastLog("没有找到对应的截图文件");
        });
     });
    
     window.robot_control.click(function(v) {
        ui.run(() => {
            if(window.robot_control.getText() == "暂停脚本")
            {
                window.robot_control.setText("开始运行");
                robot_is_running = false;
            }
            else{
                window.robot_control.setText("暂停脚本");
                robot_is_running = true;
            }
        });
      });
      window.robot_exit.click(function(v) {
          if(is_auto_clear){
            清空截图目录();
          }
          files.remove(SCREENSHOT_PATH);
          media.scanFile(SCREENSHOT_PATH); 
          files.remove(IMAGE_FILE_PATH);
          media.scanFile(IMAGE_FILE_PATH); 
          exit();
      });
    
     window.close_re.on("check", (checked)=>{
        if(checked){
            toastLog("关闭消息自动回复");
            close_auto_reply = true;
            is_multi_chat_reply = is_at_reply = false;
            window.multi_re.setChecked(false);
            window.at_re.setChecked(false);
        }else{
            toastLog("打开消息自动回复");
            close_auto_reply = false;
        }
    });
    window.multi_re.on("check", (checked)=>{
        if(checked){
            if(window.close_re.isChecked()){
                toastLog("请打开自动回复后再次进行勾选");
                window.multi_re.setChecked(false);
                is_multi_chat_reply = false;
            }
            else
            {
                // toastLog("开启群聊自动回复");
                is_multi_chat_reply = true;
            }
        }else{
            // toastLog("关闭群聊自动回复");
            is_multi_chat_reply = false;
            is_at_reply = false;
            window.at_re.setChecked(false);
        }
    });
    window.at_re.on("check", (checked)=>{
        if(checked){
            if(window.close_re.isChecked()||!window.multi_re.isChecked())
            {
                toastLog("请打开消息自动回复以及群聊回复后再次进行勾选");
                window.at_re.setChecked(false);
                is_at_reply = false;
            }
            else{
                // toastLog("开启群聊at时才自动回复");
                is_at_reply = true;
            }
        }else{
            is_at_reply = false;
        }
    });
    window.msg_screen.on("check", (checked)=>{
        if(checked){
            toastLog("开启消息截屏");
            is_screenshot_recall = true;
        }else{
            toastLog("关闭消息截屏");
            is_screenshot_recall = false;
        }
    });
    window.clear.on("check", (checked)=>{
        if(checked){
            is_auto_clear = true;
        }else{
            is_auto_clear = false;
        }
    });
    window.close_re.setChecked(close_auto_reply);
    window.multi_re.setChecked(is_multi_chat_reply);
    window.at_re.setChecked(is_at_reply);
    window.msg_screen.setChecked(is_screenshot_recall);
    window.msg_screen.setChecked(is_auto_clear);
}


function 发送信息(str)
{
    setText(str); 
    var 发送 = text("发送").clickable(true).findOne(1000);
    if(发送 != null){
        发送.click();
    }
    else{
        setText("");
    }
    sleep(350);
}
const hitokoto_c = ["c=a","c=b","c=c","c=d"];
function 每日一言()
{
    var url = 'https://v1.hitokoto.cn/?'+hitokoto_c[random(0,hitokoto_c.length-1)];
    var head = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'
    };
    var res = http.get(url, head);
    var json = res.body.json();
    return "\"" + json.hitokoto + "\" --- "  + json.from;
}
//青云客机器人
function autoReply_QYK(msg_str)
{
    var url = "http://api.qingyunke.com/api.php?key=free&appid=0&msg="+msg_str;
    var head = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'
    };
    var res = http.get(url, head);
    var json = res.body.json();
    return json.content;
}

function autoReply(name,msg)
{
    // name: "好友昵称", keyword: "再见",keyreply: "好的,再见。", enable: true,reg_enable:false,
    var flag = false;
    for(var i = 0; i < keyReplyList.length; i ++){
        if(keyReplyList[i].enable){
            if(keyReplyList[i].reg_enable){
                var reg_name = new RegExp(keyReplyList[i].name);
                var reg_keyword = new RegExp(keyReplyList[i].keyword); 
                if(reg_name.test(name) && reg_keyword.test(msg)){
                    flag = true;
                }
            }
            else{
                if(keyReplyList[i].name == '*'){//匹配任意联系人
                    if(msg.indexOf(keyReplyList[i].keyword) != -1){
                        flag = true;
                    }
                }
                else{
                    if(keyReplyList[i].name == name  && msg.indexOf(keyReplyList[i].keyword) != -1){
                        flag = true;
                    }
                }
            }
        }
        if(flag){
            发送信息(keyReplyList[i].keyreply);
            break;
        }
    }
    if(!flag){
        发送信息(autoReply_QYK(msg));
    }
}

//设置滑动页面的标题
ui.viewpager.setTitles(["主页", "设置","说明"]);
//让滑动页面和标签栏联动
ui.tabs.setupWithViewPager(ui.viewpager);

ui.keywordlist.setDataSource(keyReplyList);

ui.keywordlist.on("item_bind", function (itemView, itemHolder) {
    //绑定勾选框事件
    itemView.enable__.on("check", function (checked) {
        // toastLog("点击了"+itemHolder.position);
        if(checked){
            log("选项"+itemHolder.position+"勾选了启用");
            keyReplyList[itemHolder.position].enable = true;
        }
        else{
            log("选项"+itemHolder.position+"不勾选启用");
            keyReplyList[itemHolder.position].enable = false;
        }
        log(keyReplyList);
    });
    //绑定勾选框事件
    itemView.regenable__.on("check", function (checked) {
        // toastLog("点击了"+itemHolder.position);
        if(checked){
            log("选项"+itemHolder.position+"勾选了正则");
            keyReplyList[itemHolder.position].reg_enable = true;
        }
        else{
            log("选项"+itemHolder.position+"不勾选正则");
            keyReplyList[itemHolder.position].reg_enable = false;
        }
        log(keyReplyList);
    });
});

ui.keywordlist.on("item_click", function (item, i, itemView, listView) {
    itemView.enable__.checked = !itemView.enable__.checked;
});

ui.keywordlist.on("item_long_click", function (e, item, i, itemView, listView) {
    confirm("确定要删除关键字\"" + item.keyword + "\"吗？")
        .then(ok => {
            if (ok) {
                keyReplyList.splice(i, 1);
                log(keyReplyList);
            }
        });
    e.consumed = true;
});

//当离开本界面时保存keyReplyList
ui.emitter.on("pause", () => {
    storage.put("key_items", keyReplyList);
});

ui.add.on("click", () => {
    dialogs.rawInput("请输入好友备注")
        .then(friendname => {
            if (!friendname)  return;
            dialogs.rawInput("请输入关键字")
                .then(key_word => {
                    if(!key_word) return;
                    dialogs.rawInput("请输入回复语句")
                    .then(reply_text => {
                        if(!reply_text) return;
                        keyReplyList.push({
                            name: friendname,
                            keyword: key_word,
                            keyreply: reply_text,
                            enable: true,
                            reg_enable:false,
                        });
                    });
             });
    })
});
ui.script_start.on("click", () => {
    // toastLog("开始");
    threads.start(function(){
        launch(PACKAGE_WECHAT);
        create_floaty();
        init_floaty();
    });
});

function 聊天对象类型()
{
    chatObject_name = "NotKnowName";
    var 返回 = className("ImageView").desc("返回").findOnce();
    if(返回 == null) return OTHER_CHAT_MODE;
    var 聊天对象 = className("TextView").visibleToUser(true).filter(function(w){
        return w.text().length>0 && 返回.bounds().top<w.bounds().top && w.bounds().bottom < 返回.bounds().bottom;
    }).findOnce();
    if(聊天对象 == null) return OTHER_CHAT_MODE;
    chatObject_name = 聊天对象.text();
    var result = 聊天对象.text().match(MULTICHAT_REG);
    if(result != null && result != undefined && result.length == 1 && result[0] == 聊天对象.text())
    {
        return MULTI_CHAT_MODE;
    }
    else{
        return SINGLE_CHAT_MODE;
    }
}
function 获取本人的群昵称()
{
    var chat_manu = desc("聊天信息").findOnce();
    if(chat_manu != null)
    {
        // toastLog(window.getX()+","+window.getY()+","+window.getWidth()+","+window.getHeight());
        if(window.getX()+window.getWidth() >= chat_manu.bounds().left && chat_manu.bounds().centerY() > window.getY()){
            window.setPosition(window.getX(),chat_manu.bounds().centerY()+50);//防止遮住菜单按钮
            sleep(666);
        }
        click(chat_manu.bounds().centerX(),chat_manu.bounds().centerY());
        sleep(350);
        var 昵称 = text("我在本群的昵称").findOne(1500);
        if(昵称!=null)
        {
            var b_ = 昵称.bounds();
            var nickname = className("TextView").filter(function(w){
                var b = w.bounds();
                return w.text().length>0&&w.text()!="我在本群的昵称"&&b.top >= b_.top-50&&b.bottom <= b_.bottom+50;
            }).findOnce();//文本消息
            if(nickname != null){
                back();
                return nickname.text();
            }
        }
        back();
        return default_nickname;
    }
    return default_nickname;
}
function 初始化聊天参数()
{
    var res = 聊天对象类型();
    if(res == MULTI_CHAT_MODE){
        my_nickname = 获取本人的群昵称();
    }
    curr_chat_mode = res;
}

function getFileName()//返回一个文件名
{
   var date = new Date();
   var str = FILE_PATH + date.getFullYear()+"_"+(date.getMonth()+1)+"_"+date.getDate()+"_"
                + date.getHours()+"_"+date.getMinutes()+"_"+date.getSeconds()+"_"+file_id+".png";
   file_id ++;
   return str;
}
function 初始化截图目录()
{
   files.create(FILE_PATH);
}
// 
function 清空截图目录()
{
   files.removeDir(FILE_PATH);
}
function 截图()
{
   captureScreen(SCREENSHOT_PATH);
   return SCREENSHOT_PATH;
}
function 截图_cut(x1,y1,x2,y2)
{
   截图();
   src = images.read(SCREENSHOT_PATH);
   clip = images.clip(src, x1, y1, x2-x1, y2-y1);
   var screencut_path = getFileName();
   images.save(clip,screencut_path);
   src.recycle();
   clip.recycle();
   src = null;
   clip = null;
   return screencut_path;
}
function 申请截图权限()
{
    //申请截图权限
    threads.start(function(){
        sleep(350);
        var 立即开始 = text("立即开始").findOne(5000);
        if(立即开始 != null)
        {
            click(立即开始.bounds().centerX(),立即开始.bounds().centerY())
        }
    });
    if(!requestScreenCapture()){
        toastLog("请求截图失败");
        exit();
    }
    else toastLog("成功申请截图权限...");
}

 function pushRecallMsgToBox(msg_content,screen_path)
 {
    var newdata = new Object();
    newdata.txt=msg_content;
    newdata.src=screen_path;
    msg_recall_box.push(newdata);
 }

 MsgListPositions[0] = msgPosList_temp[0] = 0;
 RecallListPositions[0] = recallList_temp[0] = 0;
 for(var i = 1; i < MSG_MAX_SIZE; i ++)
 {
     MsgListPositions[i] = new Array(CONTENT_SIZE);
     msgPosList_temp[i] = new Array(CONTENT_SIZE);
 }

 
 function init()
 {
     if(GetWindowStatus() == UI_CHAT){
         updateContentList(getContentList());
         updateRecallList(getRecallList());
     }
 }
 
 function GetWindowStatus()
 {
     var chat_manu = desc("聊天信息").findOnce();
     var input_edit = className("android.widget.EditText").findOnce();
     if(chat_manu != null && input_edit != null){
         聊天信息 = chat_manu;
         输入框 = input_edit;
         return UI_CHAT;
     }
     var 撤回 = text("正在撤回消息").findOnce();
     if(撤回 != null) return UI_RECALLING;
     return UI_OTHER;
 }
 
 //排序消息坐标
 function selectionSort(arr,st,ed) {
     var minIndex, temp;//left,right,top,bottom,类型,值,(左or右),发送人名字
     for (var i = st; i < ed; i++) {
         minIndex = i;
         for (var j = i + 1; j <= ed; j++) {
             if (arr[j][3] < arr[minIndex][3]) {     // 寻找最小的数
                 minIndex = j;                 // 将最小数的索引保存
             }
         }
         temp = arr[i];
         arr[i] = arr[minIndex];
         arr[minIndex] = temp;
     }
     return arr;
 }
 
 function initVisit()
 {
     for(var i = 0; i < MSG_MAX_SIZE; i ++)
     {
         vis_head[i] = false;
     }
 }
 function PrintContentList(msg_arr,prex)
 {
     var str =  msg_arr[0] + ' :';
     for(var i = 1; i <= msg_arr[0]; i ++)
     {
         str = str + " [ ";
         for(var j = 0; j < CONTENT_SIZE; j ++){
             str = str + msg_arr[i][j] +",";
         }
         str = str + "] \n";
     }
     log(prex,str);
 }
 function getContentList()//left,right,top,bottom,类型,值,(左or右),发送人名字
 {
     msgPosList_temp[0] = 0;//0号单元用来计数
     var 容器列表 = classNameMatches(/.+Layout/).visibleToUser(true).clickable(true).longClickable(true).filter(function(w){
         return 聊天信息.bounds().bottom+20 < w.bounds().centerY() &&  w.bounds().centerY() < 输入框.bounds().top-60;
     }).find();
     if(容器列表.length<=1) return msgPosList_temp;
     var 头像列表 = descMatches(/.+头像/).visibleToUser(true).filter(function(w){
         return 聊天信息.bounds().bottom+20 < w.bounds().centerY() &&  w.bounds().centerY() < 输入框.bounds().top-20;
     }).find();
     if(头像列表.length <= 0) return msgPosList_temp;
     var reg = /表情.*/,head_reg = /.+头像/,content;
     // var msgPosList = new Array(容器列表.length-1);//left,right,top,bottom,类型,值,(左or右),发送人名字
     msgPosList_temp[0] = 容器列表.length-1;
     var text_selector = className("android.view.View").visibleToUser(true).clickable(true).longClickable(true).filter(function(w){
         return 聊天信息.bounds().bottom+20 < w.bounds().centerY() &&  w.bounds().centerY() < 输入框.bounds().top-60;
     });//文本消息筛选器
     var laylout_selector = classNameMatches(/.+Layout/).visibleToUser(true).clickable(true).longClickable(true).filter(function(w){
         return 聊天信息.bounds().bottom+20 < w.bounds().centerY() &&  w.bounds().centerY() < 输入框.bounds().top-60;
     });//其他消息筛选器
     var child_text_selector = textMatches(/.+/).visibleToUser(true).filter(function(w){
         return 聊天信息.bounds().bottom+20 < w.bounds().centerY() &&  w.bounds().centerY() < 输入框.bounds().top-60;
     });//文字筛选器
     var child_desc_selector = descMatches(/.+/).visibleToUser(true).filter(function(w){
         return 聊天信息.bounds().bottom+20 < w.bounds().centerY() &&  w.bounds().centerY() < 输入框.bounds().top-60;
     });//描述筛选器
     initVisit();
     remove_used_position[0] = 0;
     for(var i = 1; i < 容器列表.length; i ++)
     {
         content=容器列表[i];//left,right,top,bottom,类型,值,(左or右),发送人名字
         msgPosList_temp[i][0] = content.bounds().left;
         msgPosList_temp[i][1] = content.bounds().right;
         msgPosList_temp[i][2] = content.bounds().top;
         msgPosList_temp[i][3] = content.bounds().bottom;
         if(reg.test(content.desc()))//当前消息是表情包类型
         {
             msgPosList_temp[i][4] = EMOJI_TYPE;
             msgPosList_temp[i][5] = content.desc().substring(2);//表情包含义
         }
         else
         {
             var text_contenter = content.findOne(text_selector);
             if(text_contenter!=null)
             {
                 msgPosList_temp[i][0] = text_contenter.bounds().left;
                 msgPosList_temp[i][1] = text_contenter.bounds().right;
                 msgPosList_temp[i][2] = text_contenter.bounds().top;
                 msgPosList_temp[i][3] = text_contenter.bounds().bottom;
                 msgPosList_temp[i][4] = TEXT_TYPE;
             }
             else
             {
                 var other_contenter = content.findOne(laylout_selector);
                 msgPosList_temp[i][4] = OTHER_TYPE;
                 if(other_contenter != null)
                 {
                     msgPosList_temp[i][0] = other_contenter.bounds().left;
                     msgPosList_temp[i][1] = other_contenter.bounds().right;
                     msgPosList_temp[i][2] = other_contenter.bounds().top;
                     msgPosList_temp[i][3] = other_contenter.bounds().bottom;
                 }
             }
             var text_list = content.find(child_text_selector);
             var value = "";
             for(var k = 0; k < text_list.size(); k ++)
             {
                 value = value + text_list[k].text() + " , ";
             }
             var desc_list = content.find(child_desc_selector);
             for(var k = 0; k < desc_list.size(); k ++)
             {
                 if(!head_reg.test(desc_list[k].desc()))
                 {
                    value = value + desc_list[k].desc() + " , ";
                 }
             }
             msgPosList_temp[i][5] = value.substring(0, value.length-3);
         }
         msgPosList_temp[i][6] = LEFT;
         msgPosList_temp[i][7] = "NameUnknow";
         for(var j = 0; j < 头像列表.length; j++)
         {
             if(content.bounds().top <= 头像列表[j].bounds().centerY() 
                 && 头像列表[j].bounds().centerY() <= content.bounds().bottom)
             {
                 if(vis_head[j]){
                     remove_used_position[0]++;
                     remove_used_position[remove_used_position[0]] = i;
                 }
                 else{
                     vis_head[j] = true;
                 }
                 if(头像列表[j].bounds().centerX() < device.width/2){
                     msgPosList_temp[i][6] = LEFT;
                 }
                 else{
                     msgPosList_temp[i][6] = RIGHT;
                 }
                 msgPosList_temp[i][7] = 头像列表[j].desc().substring(0,头像列表[j].desc().length-2);
                 break;
             }
         }
     }
     // PrintContentList(msgPosList_temp,"before:");
     for(var i = remove_used_position[0]; i >= 1; i --)
     {
         for(var j = remove_used_position[i]+1; j <= msgPosList_temp[0]; j ++)
         {
             for(var k = 0; k < CONTENT_SIZE; k ++)
             {
                 msgPosList_temp[j-1][k] = msgPosList_temp[j][k];
             }
         }
         msgPosList_temp[0]--;
     }
     msgPosList_temp = selectionSort(msgPosList_temp,1,msgPosList_temp[0]);
     // PrintContentList(msgPosList_temp,"after:");
     return msgPosList_temp;
 }
 
 function updateContentList(newPosList){
     MsgListPositions[0] = newPosList[0];
     for(var i = 1; i <= newPosList[0]; i ++){
         MsgListPositions[i][0] = newPosList[i][0];MsgListPositions[i][1] = newPosList[i][1];
         MsgListPositions[i][2] = newPosList[i][2];MsgListPositions[i][3] = newPosList[i][3];
         MsgListPositions[i][4] = newPosList[i][4];MsgListPositions[i][5] = newPosList[i][5];
         MsgListPositions[i][6] = newPosList[i][6];MsgListPositions[i][7] = newPosList[i][7];
     }
 }
 function getRecallList()
 {
     var 撤回列表 = className("android.view.View").visibleToUser(true).clickable(true).filter(function(w){
         return w.text().length==0&&Math.abs((device.width/2 - w.bounds().left) - (w.bounds().right - device.width/2))<=EPS;
     }).find();
     recallList_temp[0] = 撤回列表.length;//0号单元用来计数
     for(var i = 0; i < 撤回列表.length; i++){
         recallList_temp[i+1] = 撤回列表[i].parent().bounds().top;
     }
     return recallList_temp;
 }
 function updateRecallList(recallList)
 {
     RecallListPositions[0] = recallList[0];
     for(var i = 1; i <= recallList[0]; i++){
         RecallListPositions[i] = recallList[i];
     }
 }
 function content_equal(c_a,c_b)
 {   //left,right,top,bottom,类型,值,(左or右),发送人名字
     if(Math.abs(c_a[0]-c_b[0])>EPS || Math.abs(c_a[1]-c_b[1])>EPS || Math.abs(c_a[2]-c_b[2])>EPS || Math.abs(c_a[3]-c_b[3])>EPS
         || c_a[4] != c_b[4] || c_a[5] != c_b[5] || c_a[6] != c_b[6] || c_a[7] != c_b[7]){
             return false;
     }
     return true;
 }
 //检测消息列表是否一致
 function isGetNewMsg(postList)
 {
     if(MsgListPositions[0] != postList[0]) return true;
     for(var i = 1; i <= MsgListPositions[0]; i ++){
         if(!content_equal(MsgListPositions[i],postList[i])){
             return true;
         }
     }
     return false;
 }
 
 //检测消息是否撤回
 function isRecallMsg(recallList)
 {
     if(RecallListPositions[0] >= recallList[0])
     {
         //只不过被顶上去而已
         updateRecallList(recallList);
         return false;
     }
     else{
         return true;
     }
 }
 function getMsgText(x,y)//依靠双击消息来获取消息的内容
 {
     press(x,y, 1);
     sleep (45);
     press(x,y, 1);
     sleep(600);
     // var 消息内容 = textMatches(/.+/).clickable(true).longClickable(true).findOne(1000);
     var 消息内容 = clickable(true).longClickable(true).filter(function(w){
         return w.text().length>0;
     }).findOne(1000);
     if(消息内容!=null){
         back()
         return 消息内容.text();
     }
     back();
     return "";
 }
 function addMsgToBox(content)
 {
     //left,right,top,bottom,类型,值,(左or右),发送人名字
     //  0    1    2     3    4   5      6        7
     if(content == undefined || content == null) return;
     var single_msg = new Array(HISTORY_CONTENT_SIZE);//类型,值,(左or右),发送人名字,截图路径
     single_msg[0] = content[4];
     single_msg[1] = content[5];
     single_msg[2] = content[6];
     single_msg[3] = content[7];
     if(is_screenshot_recall && content[6] == LEFT){//为了截图效率,只保存对方的截图
        // single_msg[4] = 截图_cut(content[0],content[2],content[1],content[3]);
        single_msg[4] = 截图_cut(0,content[2]-device.height/40,device.width,content[3]+device.height/40);//扩充截图范围
     }
     else single_msg[4] = DEFAULT_FILE_NAME;
     msg_box.push(single_msg);
 }
 function getMsgFromBox(cnt)//从后往前数第cnt个
 {
     if(msg_box.length == 0 || cnt > msg_box.length) return "ERROR";
     return msg_box[msg_box.length-cnt];
 }
 function deleteMsgFromBox(cnt)//从后往前数第cnt个
 {
     if(msg_box.length == 0 || cnt > msg_box.length) return ;
     msg_box.splice(msg_box.length-cnt,1);
 }
 function handleRecall(recallList)
 {
     var idx = 1,pos_y;
     var i = RecallListPositions[0],j = recallList[0];
     for(; i >=1; i --,j--)
     {
         if(Math.abs(RecallListPositions[i]-recallList[j]) > EPS){
             idx = j;
             break;
         }
     }
     pos_y = recallList[idx];
     var cnt_old = 0,err = false;
     //left,right,top,bottom,类型,值,(左or右),发送人名字
     //  0    1    2     3    4   5      6        7
     PrintContentList(MsgListPositions,"now");
     for(var k = 1; k <= MsgListPositions[0]; k ++){
         if(MsgListPositions[k][3] > pos_y){//找到第一个比 撤回标志的y坐标 大 的消息
             cnt_old = MsgListPositions[0]-k+1;
             break;
         }
     }
     if(cnt_old == 0){
         log("error,未知错误");
     }
     else
     {
         var recall_content = getMsgFromBox(cnt_old);//类型,值,(左or右),发送人名字,截图路径
         if(recall_content == "ERROR"){
             err = true;
             log("Error...");
         }
         else{
            var date = new Date();
            var time_recall = (date.getHours()<10?"0"+date.getHours():date.getHours()) + ":" + (date.getMinutes()<10?"0"+date.getMinutes():date.getMinutes());
            var recall_txt,from;
            if(curr_chat_mode == MULTI_CHAT_MODE){
                from = "在群聊\""+chatObject_name.substring(0,chatObject_name.indexOf("("))+"\"中";
            }
            else from = "在私聊中";
            if(recall_content[0] == TEXT_TYPE){//撤回的是文本类型
                if(recall_content[2] == LEFT){
                    recall_txt = recall_content[3]+"在"+time_recall+from+"撤回一条文本消息:"+recall_content[1];
                }
                else recall_txt = "本人在"+time_recall+from+"撤回一条文本消息:"+recall_content[1];
            }
            else if(recall_content[0] == EMOJI_TYPE){//撤回的是表情包
                if(recall_content[2] == LEFT){
                    recall_txt = recall_content[3]+"在"+time_recall+from+"撤回一个表情包:"+recall_content[1];
                }
                else recall_txt = "本人在"+time_recall+from+"撤回一个表情包:"+recall_content[1];
            }
            else {
                if(recall_content[2] == LEFT){
                    recall_txt = recall_content[3]+"在"+time_recall+from+"撤回一个其他类型消息:"+recall_content[1];
                }
                else recall_txt = "本人在"+time_recall+from+"撤回一个其他类型消息:"+recall_content[1];
            }
            toastLog(recall_txt);
            pushRecallMsgToBox(recall_txt,recall_content[4]);
         }
     }
     if(err){
         updateRecallList(recallList);
     }
     else{//从消息队列中删除本次记录
         deleteMsgFromBox(cnt_old);
         updateRecallList(recallList);
     }
     log(msg_box);
 }
 
 function 手动输入状态()
 {
     var chat_manu = desc("聊天信息").findOnce();
     var input_edit = className("android.widget.EditText").findOnce();
     if(chat_manu != null && input_edit != null)
     {
         聊天信息 = chat_manu;
         输入框 = input_edit;
         if(input_edit.bounds().centerY() <= device.height*4/5)
         {
             return true;
         }
     }
     return false;
 }
 function clearAll()
 {
         MsgListPositions[0] = 0;
         RecallListPositions[0] = 0;
         msg_box.length = 0;
 }
 function isAtMsg(str)
 {
    return str.indexOf("@"+my_nickname) != -1;
 }
 function handleMsg_Auto()
 {
     var msgPosList = getContentList();
     if(msgPosList[0] == 0) return;
     var recallList;
     if(isGetNewMsg(msgPosList))
     {
         sleep(350);
         msgPosList = getContentList();//缓一缓
         if(msgPosList[0] == 0) return;
         if(手动输入状态()){
             log("误判断");
             return;
         }
         recallList = getRecallList();
         if(isRecallMsg(recallList))
         {
             handleRecall(recallList);
             updateContentList(msgPosList);
         }
         else{
             updateContentList(msgPosList);
             var lastMsg = msgPosList[msgPosList[0]];
             //left,right,top,bottom,类型,值,(左or右),发送人名字
             //  0    1    2     3   4    5    6        7
             if(lastMsg[6] == RIGHT){//自己发送的消息
                //  log("是自己发送的信息");
                 lastMsg[5] = "my msg";
                 addMsgToBox(lastMsg);
                 sleep(200);
             }
             else{//别人发送的消息
                 if(lastMsg[4] == TEXT_TYPE){//文本信息
                     var msg_text = getMsgText(lastMsg[0]+5,lastMsg[2]+5);
                     while(GetWindowStatus() != UI_CHAT){//等待返回聊天界面
                         sleep(50);
                     }
                    //  toastLog("收到"+lastMsg[7]+"发送的文本信息："+msg_text);
                     lastMsg[5] = msg_text;
                     addMsgToBox(lastMsg);
                     if(!close_auto_reply){
                         if(curr_chat_mode == MULTI_CHAT_MODE)
                         {
                             if(is_multi_chat_reply && is_at_reply){
                                 if(isAtMsg(msg_text)){
                                    autoReply(lastMsg[7],msg_text);
                                 }
                             }
                             else if(is_multi_chat_reply){
                                autoReply(lastMsg[7],msg_text);
                             }
                         }
                         else if(curr_chat_mode == SINGLE_CHAT_MODE){
                            autoReply(lastMsg[7],msg_text);
                         }
                     }
                 }
                 else if(lastMsg[4] == EMOJI_TYPE){
                    //  toastLog("收到"+lastMsg[7]+"发送的表情包："+lastMsg[5]);
                     addMsgToBox(lastMsg);
                     if(!close_auto_reply){
                        if(curr_chat_mode == MULTI_CHAT_MODE)
                        {
                            if(is_multi_chat_reply && !is_at_reply){
                                if(lastMsg[5].length != 0){
                                    发送信息(autoReply_QYK(lastMsg[5]));
                                }
                                else
                                {//收到的是自定义表情包,无法解析表情包内容，随机返回"每日一言"
                                    发送信息(每日一言());
                                }
                            }
                        }
                        else if(curr_chat_mode == SINGLE_CHAT_MODE)
                        {
                            if(lastMsg[5].length != 0){
                                发送信息(autoReply_QYK(lastMsg[5]));
                            }
                            else
                            {//收到的是自定义表情包,无法解析表情包内容，随机返回"每日一言"
                                发送信息(每日一言());
                            }
                        }
                     }
                 }
                 else {
                    //  toastLog("收到其他类型信息"+lastMsg[5]);
                     addMsgToBox(lastMsg);
                     if(!close_auto_reply)
                     {
                        if(curr_chat_mode == MULTI_CHAT_MODE)
                        {
                            if(is_multi_chat_reply && !is_at_reply){
                                发送信息(每日一言());
                            }
                        }
                        else if(curr_chat_mode == SINGLE_CHAT_MODE){
                            发送信息(每日一言());
                        }
                     }
                 }
             }
         }
         sleep(300);
     }
 }
 function robot_auto_run()
 {
     init();
     var first_into_chat = true;
     var flag_switch = false;
     var window_status;
     while(true)
     {
         if(robot_is_running)
         {
            window_status = GetWindowStatus();
            if(window_status == UI_CHAT)
            {
                if(first_into_chat){//第一次进入聊天界面
                    sleep(1000);
                    first_into_chat = false;
                    updateContentList(getContentList());
                    updateRecallList(getRecallList());
                    if(GetWindowStatus() != UI_CHAT){
                        continue;
                    }
                    初始化聊天参数();
                    if(!手动输入状态()){
                        flag_switch = true;
                    }
                    else{
                        flag_switch = false;
                    }
                }
                if(!手动输入状态())
                {
                    if(flag_switch)//从手动输入更改为自动回复,需要刷新消息坐标
                    {
                        sleep(500);
                        updateContentList(getContentList());
                        updateRecallList(getRecallList());
                        flag_switch = false;
                        toastLog("切换到自动回复状态");
                    }
                    handleMsg_Auto();
                    sleep(150);
                }
                else
                {
                    if(!flag_switch){
                        sleep(300);
                        clearAll();
                        toastLog("切换到手动回复状态");
                    }
                    sleep(150);
                    flag_switch = true;//切换标志
                }
            }
            else if(window_status == UI_RECALLING){
                // sleep(1000);
                sleep(20);
                while(GetWindowStatus() != UI_CHAT){//等待返回聊天界面
                    sleep(50);
                }
            }
            else
            {
                // log("不在聊天界面");
                sleep(20);
                if(GetWindowStatus() == UI_RECALLING){
                    continue;
                }
                clearAll();
                first_into_chat = true;
            }
         }
         else
         {
            clearAll();
            first_into_chat = true;
            sleep(50);
         }
     }
 }
 threads.start(function(){
    初始化截图目录();
    申请截图权限();
    robot_auto_run();
});